package com.itdct.onflow.system.monitor.listener

import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.itdct.onflow.core.config.onflow.MonitorConfig
import com.itdct.onflow.core.extend.insertEx
import com.itdct.onflow.core.extend.logInfo
import com.itdct.onflow.core.extend.updateEx
import com.itdct.onflow.core.util.RedisUtil
import com.itdct.onflow.system.monitor.constant.SysMachineInfoConst
import com.itdct.onflow.system.monitor.entity.SysMachineInfoEntity
import com.itdct.onflow.system.monitor.manager.SysMachineInfoManager
import com.itdct.onflow.system.monitor.mapper.SysMachineInfoMapper
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty
import org.springframework.context.ApplicationListener
import org.springframework.context.event.ContextRefreshedEvent
import org.springframework.stereotype.Component
import java.util.*

/**
 * @author Zhouwx
 * @date 2025/9/5 14:10:19
 * @version 1.0
 * @description
 */
@ConditionalOnProperty(name = ["onflow.monitor.enable"], havingValue = "true")
@Component
class SysMachineRegisterListener(
    val monitorConfig: MonitorConfig,
    val sysMachineInfoMapper: SysMachineInfoMapper,
    val redisUtil: RedisUtil,
    val sysMachineInfoManager: SysMachineInfoManager
) : ApplicationListener<ContextRefreshedEvent> {
    override fun onApplicationEvent(event: ContextRefreshedEvent) {
        val machineId = monitorConfig.machineId
        val ktQueryWrapper = KtQueryWrapper(SysMachineInfoEntity::class.java)
        ktQueryWrapper.eq(SysMachineInfoEntity::machineId, machineId)
        val sysMachineInfoEntity = sysMachineInfoMapper.selectOne(ktQueryWrapper, false)
        if (sysMachineInfoEntity == null) {
            logInfo("注册新服务器信息到数据库")
            val machineInfo = sysMachineInfoManager.getMachineInfo()
            sysMachineInfoMapper.insertEx(machineInfo)
        } else {
            sysMachineInfoEntity.onlineState = SysMachineInfoConst.ONLINE
            sysMachineInfoEntity.lastReportDate = Date()
            sysMachineInfoMapper.updateEx(sysMachineInfoEntity)
        }

    }

}